package com.rpp.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @Description
 * @Author peng
 * @Date 2020/7/8 1:24 下午
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (uri.indexOf("js") > 0) {
            return true;
        }
        if (uri.indexOf("css") > 0) {
            return true;
        }

        HttpSession session = request.getSession();
        System.out.println("===>>>sessionId:" + session.getId());
        System.out.println("===>>>SESSION:" + session);

        Enumeration<String> attrs = session.getAttributeNames();
        // 遍历attrs中的
        while (attrs.hasMoreElements()) {
            // 获取session键值
            String name = attrs.nextElement();
            // 根据键值取session中的值
            Object vakue = session.getAttribute(name);
            // 打印结果
            System.out.println("------" + name + ":" + vakue + "--------\n");
        }

        System.out.println("===>>>当前uri：" + request.getRequestURI());
        Object username = session.getAttribute("username");
        System.out.println("===>>>username:" + username);
        if (username == null) {
            // 没有登录,重定向到登录页
            System.out.println("===>>>未登录，请登录");
            response.sendRedirect(request.getContextPath() + "/user/toLogin");
            return false;
        } else {
            System.out.println("===>>>已登录，放行请求");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
